<template>
  <div class="player">
    <div class="music-info">
      <div key="1" class="image ml10" @click="handleDrawer">
        <img :src="img" alt="" />
        <span class="iconfont icon-xiangshangjiantou xiangshang"></span>
      </div>
      <div class="info ml10">
        <div class="songName fw500 p5 oh">{{ songName }}</div>
        <div class="singer f14 p5 oh">{{ singer }}</div>
      </div>
      <div class="love ml10">
        <span style="fontSize: 20px" class="iconfont icon-aixin-xian"></span>
      </div>
    </div>
    <div class="player-control">
      <div class="control">
        <span style="fontSize: 25px" class="iconfont icon-suijibofang"></span>
        <span style="fontSize: 25px" class="iconfont icon-diyiyeshouyeshangyishou"></span>
        <span v-if="!musicStore.isPlay" style="fontSize: 40px" class="iconfont icon-24gf-playCircle" @click="play"></span>
        <span v-else style="fontSize: 40px" class="iconfont icon-24gf-pauseCircle" @click="play"></span>
        <span style="fontSize: 25px" class="iconfont icon-zuihouyiyemoyexiayishou"></span>
        <span style="fontSize: 20px" class="iconfont icon-shengyin_shiti"></span>
        <audio ref="audio" preload="auto" :src="curPlayMusicUrl" @canplay="getDuration" @timeupdate="updateTime"></audio>
      </div>
      <div class="process">
        <div class="time tac">{{ audioObj.currentTime }}</div>
        <div class="progress" ref="progress" @click="clickProgress" @mouseup="handleMouseup">
          <div class="currentProgress" ref="currentProgress">
            <span class="circle" ref="circle" @mousedown="handleMousedown"></span>
          </div>
        </div>
        <!-- <el-progress ref="progress" class="progress" :percentage="audioObj.percentage" :stroke-width="3" status="success" style="width: 100%" color="#18a058" :show-text="false" /> -->
        <div class="time tac">{{ audioObj.duration }}</div>
      </div>
    </div>
    <div class="music-list mr10">
      <span class="iconfont icon-liebiao" style="fontSize: 25px"></span>
    </div>
  </div>
  <el-drawer
    v-model="isLyrics"
    direction="ttb"
    :with-header="false"
    custom-class="drawer"
    modal-class="drawer2"
    size="100%"
  > 
    <div class="scrollbar">
      <div class="exit">
        <span style="fontSize: 20px" class="iconfont icon-xiangxiajiantou" @click="isLyrics=!isLyrics"></span>
      </div>
      <el-scrollbar class="text">
        <ul ref="lyricUL">
          <li 
            v-for="(item, i) in lyricsObjArr"
            :style="{color: lyricIndex === i ? color1 : color2,fontWeight : lyricIndex === i?'700':normal,fontSize: lyricIndex === i ?'medium':'small'}" 
            :key="item.uid" :data-index='i' 
            ref="lyric"
          >{{item.lyric}}</li>
        </ul>
      </el-scrollbar>
    </div>
  </el-drawer>
</template>

<script>
import { computed, ref, onMounted, reactive, watchEffect, watch,nextTick ,getCurrentInstance } from 'vue'
import { useMusicStore } from '@/store/music.js'
import { useDark } from '@vueuse/core'
import { useUserStore } from '@/store/userInfo.js'
const userStore=useUserStore()
const musicStore = useMusicStore()

import { ElMessage } from 'element-plus'
export default {
  setup() {
    const {proxy}=getCurrentInstance()
    const musicStore = useMusicStore()
    const isPlay=computed(()=>{
      return musicStore.isPlay
    })
    const color1=computed(()=>{
      return userStore.isDark?'#63e2b7':'#000000'
    })
    const color2=computed(()=>{
      return userStore.isDark?'#666666':'#666666'
    })
    const url=computed(()=>{
      return musicStore.curPlayMusicUrl
    })
    watch(isPlay,(newValue)=>{
      if(musicStore.curPlayMusicUrl==null){
        return ElMessage.error('当前歌曲暂无版权')
      }
      if(isPlay.value){
        console.log("执行了play()");
        nextTick(async()=>{
          audio.value.play()
        })
      }else{
        nextTick(async()=>{
          audio.value.pause()
        })
      }
    })
    watch(url,(newValue)=>{
      if(musicStore.curPlayMusicUrl==null){
        return ElMessage.error('当前歌曲暂无版权')
      }
      if(isPlay.value){
        nextTick(async()=>{
          audio.value.play()
        })
      }else{
        nextTick(async()=>{
          audio.value.pause()
        })
      }
    })
    // 歌曲信息
    let songName = computed(() => {
      return musicStore.curMusicInfo.name
    })
    let singer = computed(() => {
      if (musicStore.curMusicInfo.song == undefined) {
        if (musicStore.curMusicInfo.ar == undefined) {
          return '未知歌手'
        } else {
          return musicStore.curMusicInfo.ar.map((item) => item.name).join(' / ')
        }
      } else {
        return musicStore.curMusicInfo.song.artists.map((item) => item.name).join(' / ')
      }
    })
    let img = computed(() => {
      if (musicStore.curMusicInfo.al) {
        return musicStore.curMusicInfo.al.picUrl
      } else {
        return ''
      }
      // if(musicStore.curMusicInfo.picUrl){
      //   return musicStore.curMusicInfo.picUrl
      // }else{
      //   return musicStore.curMusicInfo.al.picUrl
      // }
    })
    let curPlayMusicUrl = computed(() => {
      return musicStore.curPlayMusicUrl
    })

    // 播放
    const audio = ref(null)
    let lyricUL=ref(null)
    let lyric=ref(null)
    let lyricIndex=ref(0)
    let play = async () => {
      if(musicStore.curPlayMusicUrl==null){
        return ElMessage.error('当前歌曲地址为空！')
      }
      if (audio.value.paused) {
        musicStore.setIsPlay(audio.value.paused)
      } else {
        musicStore.setIsPlay(audio.value.paused)
      }
    }
    let audioObj = reactive({
      paused: true,
      percentage: 0,
      duration: '00:00',
      currentTime: '00:00',
    })
    let lyricsObjArr=ref([])
    let getMusicText=async()=>{
      let id=musicStore.curMusicInfo.id
      let {lrc}=await proxy.$api.getMusicText({id})
      lrc.value=lrc.lyric
      const regNewLine = /\n/
      const lineArr = lrc.value.split(regNewLine)
      const regTime = /\[\d{2}:\d{2}.\d{2,3}\]/
      lineArr.forEach(item => {
      if (item === '') return
        const obj = {}
        const time = item.match(regTime)
        obj.lyric = item.split(']')[1].trim() === '' ? '' : item.split(']')[1].trim()
        obj.time = time ? formatLyricTime(time[0].slice(1, time[0].length - 1)) : 0
        obj.uid = Math.random().toString().slice(-6)
        if (obj.lyric === '') {
          console.log('这一行没有歌词')
        } else {
          lyricsObjArr.value.push(obj)
        }
      })
      console.log(lyricsObjArr.value);
    }
    let formatLyricTime=(time)=> { // 格式化歌词的时间 转换成 sss:ms
     const regMin = /.*:/
     const regSec = /:.*\./
     const regMs = /\./
     const min = parseInt(time.match(regMin)[0].slice(0, 2))
     let sec = parseInt(time.match(regSec)[0].slice(1, 3))
     const ms = time.slice(time.match(regMs).index + 1, time.match(regMs).index + 3)
     if (min !== 0) {
       sec += min * 60
     }
     return Number(sec + '.' + ms)
    }
    let isLyrics=ref(false)
    let lrc=ref()
    let handleDrawer=async()=>{
      isLyrics.value=!isLyrics.value
      await getMusicText()
    }
    onMounted(async () => {
      if(musicStore.isPlay){
        musicStore.isPlay=false
      }
      // 音乐全部加载完毕周期函数，格式化总时长
      audio.value.addEventListener('canplaythrough', async function () {
        let fen = Math.floor(audio.value.duration / 60)
        if (!fen) {
          audio.value.duration > 10 ? (audioObj.duration = '00:' + Math.floor(audio.value.duration)) : (audioObj.duration = '00:0' + Math.floor(audio.value.duration))
        } else {
          let yu = Math.floor(audio.value.duration % 60)
          if (fen > 9) {
            yu > 9 ? (audioObj.duration = fen + ':' + yu) : (audioObj.duration = fen + ':0' + yu)
          } else {
            yu > 9 ? (audioObj.duration = '0' + fen + ':' + yu) : (audioObj.duration = '0' + fen + ':0' + yu)
          }
        }
      })
      // 时间改变周期函数，计算进度条,格式化当前时间
      audio.value.addEventListener('timeupdate', function () {
        audioObj.percentage = Math.floor((audio.value.currentTime / audio.value.duration) * 100)
        let fen = Math.floor(audio.value.currentTime / 60)
        if (!fen) {
          audio.value.currentTime > 10 ? (audioObj.currentTime = '00:' + Math.floor(audio.value.currentTime)) : (audioObj.currentTime = '00:0' + Math.floor(audio.value.currentTime))
        } else {
          let yu = Math.floor(audio.value.currentTime % 60)
          if (fen > 9) {
            yu > 9 ? (audioObj.currentTime = fen + ':' + yu) : (audioObj.currentTime = fen + ':0' + yu)
          } else {
            yu > 9 ? (audioObj.currentTime = '0' + fen + ':' + yu) : (audioObj.currentTime = '0' + fen + ':0' + yu)
          }
        }
        if (audio.value.currentTime == audio.value.duration) {
          musicStore.setIsPlay(false)
        }
        // if (audioObj.currentTime == '00:00') {
        //   musicStore.setIsPlay(false)
        //   audioObj.percentage = 0
        // }
        for (let i = 0; i < lyricsObjArr.value.length; i++) {
          if (audio.value.currentTime > (parseInt(lyricsObjArr.value[i].time))) {
            const index = lyric.value[i].dataset.index
            if (i === parseInt(index)) {
              lyricIndex.value = i
              lyricUL.value.style.transform = `translateY(${-(lyricUL.value.style.height) - (40 * (i-4))-10}px)`
            }
          }
        }
      })
    })
    let progress = ref(null)
    return {
      musicStore,
      songName,
      singer,
      img,
      curPlayMusicUrl,
      audio,
      play,
      audioObj,
      progress,
      handleDrawer,
      isLyrics,
      lrc,
      formatLyricTime,
      lyricsObjArr,
      lyricUL,
      lyric,
      lyricIndex,
      color1,
      color2
    }
  },
  props: {
    audioSrc: {
      type: String,
      default: 'https://img-qn.51miz.com/Audio/2017/02/06/08/20170206081849_A100187_34f7e6b8-thumb.mp3',
    },
    backSecond: {
      type: Number,
      default: 3,
    },
    forwardSecond: {
      type: Number,
      default: 10,
    },
  },
  data() {
    return {
      duration: '00:00',
      currentDuration: '00:00',
      audio: '',
      paused: true,
      isMoveIn: false, //是否在移动中
      url:musicStore.curPlayMusicUrl,
      imageIsShow:true
    }
  },
  watch:{
    url(){
      this.duration='00:00'
    }
  },
  methods: {
    //后退
    handleBack() {
      if (this.audio.currentTime > this.backSecond) {
        this.audio.currentTime = this.audio.currentTime - this.backSecond
      }
    },
    //前进
    handleForward() {
      if (this.audio.duration - this.audio.currentTime > this.forwardSecond) {
        this.audio.currentTime = this.audio.currentTime + 10
      }
    },
    //暂停或播放
    handlePauseOrPlay() {
      this.audio.paused ? this.audio.play() : this.audio.pause()
      this.paused = !this.paused
    },
    //视频在可以播放时触发
    getDuration() {
      this.duration = this.timeFormat(this.$refs.audio.duration)
      this.audio = this.$refs.audio
    },
    //将单位为秒的的时间转换成mm:ss的形式
    timeFormat(number) {
      let minute = parseInt(number / 60)
      let second = parseInt(number % 60)
      minute = minute >= 10 ? minute : '0' + minute
      second = second >= 10 ? second : '0' + second
      return minute + ':' + second
    },
    //进度条发生变化时触发
    updateTime() {
      if (!this.$refs.progress) return
      this.currentDuration = this.timeFormat(this.audio.currentTime)
      //如果不是正在移动 和 没有暂停播放就执行
      if (!this.isMoveIn || !this.audio.paused) {
        // 设置当前时间
        let MoveX = this.$refs.progress.clientWidth * (this.audio.currentTime / this.audio.duration)
        //播放时更新距离
        this.$refs.currentProgress.style.width = MoveX + 'px'
        this.$refs.circle.style.left = MoveX - this.$refs.circle.clientWidth / 2 + 'px'
      }
    },
    //点击进度条更新进度
    clickProgress(e) {
      //如果不是正在移动 和 没有暂停播放就执行
      if (!this.isMoveIn || !this.audio.paused) {
        this.updateProgress(e.offsetX)
      }
    },
    //更新进度
    updateProgress(MoveX) {
      //当前移动的位置 = 当前移动的位置 / 当前进度条的可视长度    //this.$refs.progress.clientWidth 注意一定要拿总长度 否则会拿进度条已经走过的长度
      let clickProgress = MoveX / this.$refs.progress.clientWidth
      //设置播放的时间 = 总时长 * 当前点击的长度
      this.audio.currentTime = this.audio.duration * clickProgress
      //设置移动的位置
      this.$refs.currentProgress.style.width = MoveX + 'px'
      this.$refs.circle.style.left = MoveX - this.$refs.circle.clientWidth / 2 + 'px'
    },
    //鼠标弹起
    handleMouseup() {
      setTimeout(() => {
        this.audio.play()
        this.paused = false
        this.isMoveIn = false
      }, 200)
    },
    //小圆圈按下
    handleMousedown() {
      this.audio.pause()
      this.paused = true
      this.isMoveIn = true
      let progress = this.$refs.progress
      //进度条 左 边距离页面左边的距离 移动最小值
      let moveMin = progress.offsetParent.offsetLeft + progress.offsetLeft
      //进度条 右 边距离页面左边的距离 移动最大值
      let moveMax = progress.offsetParent.offsetLeft + progress.offsetLeft + progress.clientWidth
      //小圆圈的宽度
      let circleWidth = this.$refs.circle.clientWidth / 2
      let move = (move) => {
        if (move.pageX >= moveMax) {
          return
        } else if (move.pageX <= moveMin) {
          return
        }
        this.$refs.circle.style.left = move.pageX - moveMin - circleWidth + 'px'
        this.updateProgress(move.pageX - moveMin)
      }
      //获取当前鼠标的位置 X
      document.addEventListener('mousemove', move)
      //鼠标弹起来
      document.addEventListener('mouseup', () => {
        document.removeEventListener('mousemove', move)
      })
    },
  },
}
</script>

<style lang="scss">
.player {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .music-info {
    width: 250px;
    height: 100%;
    display: flex;
    align-items: center;
    .image {
      position: relative;
      width: 60px;
      height: 60px;
      img {
        width: 60px;
        z-index: -1;
      }
      .iconfont{
        z-index: 1;
        opacity: 0;
        position: absolute;
        left: 20px;
        top: 25px;
      }
    }
    .image:hover{
      img{
        filter: blur(2px);
      }
      .iconfont{
        opacity: 1;
      }
    }
    .singer {
      max-width: 120px;
    }
    .songName {
      max-width: 120px;
    }
  }
  .player-control {
    width: 800px;
    height: 100%;
    display: flex;
    flex-direction: column;
    .control {
      margin: auto;
      width: 60%;
      height: 50px;
      display: flex;
      justify-content: space-around;
      align-items: center;
    }
    .process {
      width: 100%;
      height: 25px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .time {
        width: 100px;
        font-size: 14px;
        line-height: 25px;
        height: 25px;
      }
    }
  }
  .music-list {
    width: 250px;
    display: flex;
    justify-content: end;
  }
}
.progress {
  height: 4px;
  border-radius: 2px;
  margin-bottom: 0px;
  width: 100%;
  background-color: #daeae2;
  cursor: pointer;

  .currentProgress {
    position: relative;
    height: 100%;
    width: 0;
    background-color: #02b402;
    border-radius: 3px;

    .circle {
      position: absolute;
      right: -6px;
      top: -2px;
      display: inline-block;
      width: 6px;
      height: 6px;
      border-radius: 50%;
      border: 1px solid #3853fe;
      background-color: #fff;

      &:hover {
        width: 8px;
        height: 8px;
        top: -3px;
        border-radius: 50%;
      }
    }
  }
}
.image-enter,.image-leave-to{
  transform: translateY(100%);
}
.image-enter-to,.image-leave{
  transform: translateY(0);
}
.image-enter-active,.image-leave-active{
  transition: 0.5s linear;
}

.drawer2{
  box-shadow: none;
}
.xiangshang{
  color: #fff;
}
.dark{
  .xiangshang{
    color: rgb(255, 255, 255);
  }
}
.scrollbar{
  padding: 0;
  margin: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
  .exit{
    height: 30px;
  }
  .text{
    ul{
      li{
        list-style: none;
        text-align: center;
        height: 40px;
        line-height: 40px;
      }
    }
    flex: 1;
    width: 700px;
    margin: auto;
  }
}
.el-scrollbar__bar{
  display: none;
}

</style>
